#ifndef STREMINGSERVERCONNECTION
#define STREMINGSERVERCONNECTION

#include <app\session.h>

#include <vector>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread/condition_variable.hpp>

using boost::asio::ip::tcp;
using namespace std;

#define MAX_TICKETS 20

class serialize {

  boost::mutex input_mutex;
  int current_ticket;
  int last_ticket;

public:

  serialize();
  int getTicket();
  void relaseTicket(int ticket);
};

class streamingConnection {

  tcp::socket socket_;
  boost::asio::io_service& io_service_;

  session my_session;

  enum { 
    max_length = 1024 
  };

  char data_[max_length];

  boost::mutex input_mutex;
  serialize serializator;
  stringstream *input_bytes;
  unsigned int input_bytes_count;
  unsigned int input_command_size;

  boost::mutex output_mutex;
  bool write_in_progress;
  vector<unsigned char *> output_bytes;
  vector<unsigned int>    output_bytes_size;
  
private:

  void receiveBytes(size_t bytes_transferred);

public:

  session &getSession();
  tcp::socket& socket();

  void start();

  void sendData(unsigned char *bytes, int size);
  void writeBytes(unsigned char *bytes, int size);

  void handle_read(const boost::system::error_code& error, size_t bytes_transferred);
  void handle_write(const boost::system::error_code& error, size_t bytes_transferred);

  streamingConnection(boost::asio::io_service& io_service);
};

#endif
